import ImgPreview from "@/components/dataPresentation/ImgPreview";
import { useUploadImage } from "@/hooks";
import { PlusOutlined, EyeOutlined, DeleteOutlined, EditOutlined } from "@ant-design/icons";
import { Button, Form, Input, InputNumber, Popconfirm, Switch, Tooltip, FormInstance } from "antd";
import { cloneDeep } from "lodash";
import { useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
import { ConfigurePageContext } from "../../ConfigurePage";
import { StyledCatEditorWrapper, StyledIconWrapper, StyledUploadButton } from "../../ConfigurePage.styled";
import { CatItem } from "../../ConfigurePageType";
interface CatFields extends Omit<CatItem, "borderRadius"> {
	status: boolean;
	rows: number;
	columns: number;
	borderRadius: number;
}
const CatEditor = () => {
	const { content, selectedIndex, setContent } = useContext(ConfigurePageContext);
	if (selectedIndex === null) return <></>;
	const list = useMemo(() => (content[selectedIndex].list as CatItem[]) || [], [content, selectedIndex]);
	const imgCommonStyle = { width: "120px", height: "120px" };
	const [selectedIconIndex, setSelectedIconIndex] = useState<number | null>(null);
	const iconSrcIndex = useRef<number>();
	const isReplaceIcon = useRef(false);
	const [previewSrc, setPreviewSrc] = useState("");
	const [radiusType, setRadiusType] = useState<"pixel" | "percent">("pixel");
	const [sizeType, setSizeType] = useState<"pixel" | "rpx">("pixel");
	const initialIconItem = { name: "", size: "80px", borderRadius: "50%", link: "", rows: 2, columns: 5 };
	const { upload } = useUploadImage((path) => {
		if (iconSrcIndex.current === undefined) return;
		const copiedContent = cloneDeep(content);
		if (isReplaceIcon.current) {
			(copiedContent[selectedIndex].list[iconSrcIndex.current] as CatItem).icon = path;
		} else {
			(copiedContent[selectedIndex].list as CatItem[]).splice(iconSrcIndex.current, 0, { icon: path, ...initialIconItem });
		}
		setContent(copiedContent);
	});
	const handleClickUpload = (index: number) => {
		iconSrcIndex.current = index;
		isReplaceIcon.current = false;
		upload();
	};
	const handleValuesChange = useCallback(
		(_: unknown, fields: CatFields) => {
			const {
				status,
				rows = initialIconItem.rows,
				columns = initialIconItem.columns,
				size = initialIconItem.size,
				borderRadius = initialIconItem.borderRadius,
			} = fields;
			const copiedContent = cloneDeep(content);
			copiedContent[selectedIndex] = {
				...copiedContent[selectedIndex],
				status,
				rows,
				columns,
				list: copiedContent[selectedIndex].list.map((item, index) => {
					return {
						...copiedContent[selectedIndex].list[index],
						size: size + (sizeType === "rpx" ? "rpx" : "px"),
						borderRadius: borderRadius + (radiusType === "percent" ? "%" : "px"),
					};
				}),
			};
			if (selectedIconIndex !== null) {
				const { name, link, description = "" } = catForm.current?.getFieldsValue() as CatFields;
				copiedContent[selectedIndex].list[selectedIconIndex] = {
					...copiedContent[selectedIndex].list[selectedIconIndex],
					name,
					link,
					description,
				};
			}
			setContent(copiedContent);
		},
		[content, selectedIndex, selectedIconIndex, radiusType]
	);
	const catForm = useRef<FormInstance<CatFields> | null>(null);
	useEffect(() => {
		const { status = true } = content[selectedIndex];
		const iconItem = (content[selectedIndex]?.list?.[selectedIconIndex || 0] as CatItem) || {};
		const { borderRadius } = iconItem;
		if (borderRadius) {
			if (String(borderRadius).endsWith("%")) {
				setRadiusType("percent");
			} else {
				setRadiusType("pixel");
			}
		}
		const { size } = iconItem;
		const { rows = 2, columns = 5 } = content[selectedIndex];
		const options: Partial<Omit<CatFields, "borderRadius">> & { borderRadius?: number } = {
			status,
			rows,
			columns,
			size,
		};
		if (borderRadius !== undefined) {
			options.borderRadius = +borderRadius.replaceAll("%", "").replaceAll("px", "");
		}
		catForm.current?.setFieldsValue(options);
	}, []);

	const replaceRadiusType = useCallback(() => {
		setRadiusType(radiusType === "pixel" ? "percent" : "pixel");
		const copiedContent = cloneDeep(content);
		let borderRadius = catForm.current?.getFieldValue("borderRadius");
		if (borderRadius === undefined) return;
		catForm.current?.setFieldValue("borderRadius", borderRadius);
		if (radiusType === "pixel") {
			// 转百分比
			borderRadius += "%";
		} else {
			// 转像素
			borderRadius += "px";
		}
		(copiedContent[selectedIndex].list as CatItem[]).forEach((item) => (item.borderRadius = borderRadius));
		setContent(copiedContent);
	}, [radiusType, content, selectedIndex]);
	const replaceSizeType = useCallback(() => {
		setSizeType(sizeType === "pixel" ? "rpx" : "pixel");
		const copiedContent = cloneDeep(content);
		let size = catForm.current?.getFieldValue("size");
		if (size === undefined) return;
		catForm.current?.setFieldValue("size", size);
		if (sizeType === "pixel") {
			// 转百分比
			size += "rpx";
		} else {
			// 转像素
			size += "px";
		}
		(copiedContent[selectedIndex].list as CatItem[]).forEach((item) => (item.size = size));
		setContent(copiedContent);
	}, [sizeType, content, selectedIndex]);
	const clickIcon = useCallback(
		(index: number) => {
			const currentIndex = selectedIconIndex === index ? null : index;
			setSelectedIconIndex(currentIndex);
			if (currentIndex === null) return;
			const { name, link, description } = (content[selectedIndex].list[index] as CatItem) || {
				name: "",
				link: "",
				description: "",
			};
			catForm.current?.setFieldsValue({ name, link, description });
		},
		[content, selectedIndex, selectedIconIndex]
	);
	return (
		<StyledCatEditorWrapper className="overflow-y-scroll">
			<div className="flex flex-wrap">
				{list.map((item, index) => (
					<StyledIconWrapper
						key={index}
						onClick={() => clickIcon(index)}
						style={{ ...imgCommonStyle, border: `2px dashed ${selectedIconIndex === index ? "red" : "transparent"}` }}
						className="relative cursor-pointer mr-3 mb-2 rounded-full overflow-hidden"
					>
						<img
							src={`${process.env.REACT_APP_BASEURL}${item.icon}`}
							style={imgCommonStyle}
							className="rounded-full object-center object-cover"
						/>
						<div className="mask absolute top-0 bottom-0 left-0 right-0 justify-center items-center rounded-full">
							<Tooltip title="删除图标" placement="bottom">
								<Popconfirm
									title="确认删除吗？"
									onConfirm={(e) => {
										e?.stopPropagation();
										const copiedContent = cloneDeep(content);
										copiedContent[selectedIndex].list.splice(index, 1);
										setContent(copiedContent);
										if (selectedIconIndex === index) {
											setSelectedIconIndex(null);
										}
									}}
								>
									<Button
										onClick={(e) => e.stopPropagation()}
										shape="circle"
										size="small"
										danger
										icon={<DeleteOutlined />}
									/>
								</Popconfirm>
							</Tooltip>
							<Tooltip title="预览">
								<Button
									onClick={(e) => {
										setPreviewSrc(item.icon);
										e.stopPropagation();
									}}
									className="mx-1"
									icon={<EyeOutlined />}
									size="small"
									shape="circle"
								/>
							</Tooltip>
							<Tooltip title="重新上传图片">
								<Button
									onClick={(e) => {
										isReplaceIcon.current = true;
										iconSrcIndex.current = index;
										e.stopPropagation();
										upload();
									}}
									className="mr-1"
									type="primary"
									icon={<EditOutlined />}
									size="small"
									shape="circle"
								/>
							</Tooltip>
							<Tooltip title="在后面添加图标">
								<Button
									onClick={(e) => {
										e.stopPropagation();
										isReplaceIcon.current = false;
										iconSrcIndex.current = index + 1;
										upload();
									}}
									shape="circle"
									type="primary"
									size="small"
									icon={<PlusOutlined />}
								/>
							</Tooltip>
						</div>
					</StyledIconWrapper>
				))}
				<StyledUploadButton
					style={{ ...imgCommonStyle, fontSize: "25px" }}
					onClick={() => handleClickUpload(list.length + 1)}
					className="rounded-full border-dashed border-slate-400 flex justify-center items-center cursor-pointer"
				>
					<PlusOutlined style={{ color: "rgb(148 163 184)" }} />
				</StyledUploadButton>
			</div>
			<Form
				ref={catForm}
				onValuesChange={handleValuesChange}
				className="mt-4"
				labelAlign="left"
				labelCol={{ style: { width: "150px" } }}
				wrapperCol={{ span: 18 }}
			>
				<Form.Item label="状态" name="status" valuePropName="checked">
					<Switch checkedChildren="启用" unCheckedChildren="禁用" />
				</Form.Item>
				<Form.Item label="行数" name="rows">
					<InputNumber min={1} placeholder="请输入行数" style={{ width: "200px" }} />
				</Form.Item>
				<Form.Item label="列数" name="columns">
					<InputNumber min={1} placeholder="请输入列数" style={{ width: "200px" }} />
				</Form.Item>
				{/* <Form.Item label="图标大小" name="size">
					<InputNumber min={0} placeholder="请输入图标大小" style={{ width: "200px" }} />
				</Form.Item> */}
				<div className="flex">
					<Form.Item labelCol={{ style: { width: "150px" } }} label="图标大小" name="size">
						<InputNumber
							addonAfter={sizeType === "pixel" ? "px" : "rpx"}
							min={0}
							placeholder="请输入图标大小"
							style={{ width: "200px" }}
						/>
					</Form.Item>
					<Tooltip title={`替换为${sizeType === "pixel" ? "rpx" : "像素"}`}>
						<i onClick={replaceSizeType} className="iconfont icon-tihuan ml-3 mt-1 text-lg cursor-pointer" />
					</Tooltip>
				</div>
				<div className="flex">
					<Form.Item labelCol={{ style: { width: "150px" } }} label="圆角大小" name="borderRadius">
						<InputNumber
							addonAfter={radiusType === "pixel" ? "px" : "%"}
							min={0}
							placeholder="请输入圆角大小"
							style={{ width: "200px" }}
						/>
					</Form.Item>
					<Tooltip title={`替换为${radiusType === "pixel" ? "百分比" : "像素"}`}>
						<i onClick={replaceRadiusType} className="iconfont icon-tihuan ml-3 mt-1 text-lg cursor-pointer" />
					</Tooltip>
				</div>
				{selectedIconIndex !== null && (
					<div className="ml-44">
						<Form.Item label="分类名称" name="name">
							<Input placeholder="请输入分类名称" style={{ width: "200px" }} />
						</Form.Item>
						<Form.Item label="跳转链接" name="link">
							<Input.TextArea placeholder="请输入跳转链接" />
						</Form.Item>
						<Form.Item label="描述" name="description">
							<Input.TextArea placeholder="请输入描述" />
						</Form.Item>
					</div>
				)}
			</Form>
			<ImgPreview src={previewSrc} onHide={() => setPreviewSrc("")} />
		</StyledCatEditorWrapper>
	);
};

export default CatEditor;
